package dama.dama2;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.CookieStore;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.*;
import java.net.URL;

/**
 * Created by Administrator on 2014/4/3.
 * Time: 15:32
 */
public class CheckCodeSubmit {

    static String checkcode = "";

    public static String submit(String codeimg, String checkurl, String sessionID,CookieStore cookieStore)  {
        String result = "";
        do {
            //获取一个验证码字符串
            while (true) {
                try {
                    checkcode = dama3(codeimg);
                } finally {

                }
                System.out.println(checkcode);
                if (!checkcode.equals("ERROR")) break;
            }

            System.out.println("获得验证码：" + checkcode);
            //拼接字符串提交验证码
            String add = "http://sec.taobao.com/query.htm?";
            checkurl = checkurl.substring(checkurl.indexOf("?") + 1);
            add += "sessionID=" + sessionID + "&";
            add += "code=" + checkcode + "&";
            add += "_ksTS=" + System.currentTimeMillis() + "_111" + "&";
            add += "callback=" + "shop_rate_list" + "&";
            add += checkurl;
            System.out.println("提交到地址：" + add);
            result = getStrByUrl(add,cookieStore);
            System.out.println("提交结果" + result);
            System.out.println(isCheckCode(result));
        } while (isCheckCode(result));
        return result;
    }

    private static Dama2Web dama2 = new Dama2Web(10982, "547cd24e002556d68597b54b1df7d5a5", "test", "test");

    public static String dama2(String codeimg) {
        int type = 42;
        int timeout = 30;
        String url = codeimg;
        Dama2Web.DecodeResult res = dama2.decodeUrlAndGetResult(url, type, timeout);
        String s;
        if (res.ret >= 0) {
            //int id = res.ret;
            //s = "success: result=" + res.result + "; id=" + res.ret;
            s = res.result;
        } else {
            //s = "failed: ret = " + res.ret + "; desc=" + res.desc ;
            s = "ERROR";
        }
        return s;
    }


    public static String dama3(String codeimg)  {
        int type = 42;
        int timeout = 30;
        //1、使用IOUtils
        InputStream in = null;
        try {
            in = new URL(codeimg).openStream();
        } catch (IOException e) {
            e.printStackTrace();
        }

        ByteArrayOutputStream outStream = new ByteArrayOutputStream();

        byte[] buffer = new byte[1000];
        int count = -1;
        try {
            while ((count = in.read(buffer, 0, 1000)) != -1)

                outStream.write(buffer, 0, count);
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] data = outStream.toByteArray();
        System.out.println(data);

        Dama2Web.DecodeResult res = dama2.decodeAndGetResult(type, timeout, data);
        String s;
        if (res.ret >= 0) {

            s = "success: result=" + res.result + "; id=" + res.ret;
        } else {
            s = "failed: ret = " + res.ret + "; desc=" + res.desc;
        }
        return s;
    }

    /**
     * 通过httpclient 提交get方法的ajax请求
     *
     * @param url 地址
     * @return json字符串
     * @throws java.io.IOException
     */
    public static String getStrByUrl(String url,CookieStore cookieStore) {
        StringBuilder entityStringBuilder = new StringBuilder();
        BufferedReader bufferedReader = null;
        String s1 = null;


        CloseableHttpClient httpclient = HttpClients.custom()
                .setDefaultCookieStore(cookieStore).build();
        HttpGet httpget = new HttpGet(url);
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build();
        httpget.setConfig(requestConfig);
        CloseableHttpResponse response = null;
        try {
            response = httpclient.execute(httpget);
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            HttpEntity httpEntity = response.getEntity();
            if (httpEntity != null) {
                try {
                    bufferedReader = new BufferedReader
                            (new InputStreamReader(httpEntity.getContent(), "GBK"), 8 * 1024);
                    String line = null;
                    while ((line = bufferedReader.readLine()) != null) {
                        entityStringBuilder.append(line + "/n");

                    }
                    // FileUtils.writeStringToFile(dest, entityStringBuilder.toString(), "GBK");
                    s1 = entityStringBuilder.subSequence(entityStringBuilder.toString().indexOf("{"), entityStringBuilder.toString().lastIndexOf("}") + 1).toString();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println("解析地址：" + url);

        return s1;
    }

    public static boolean isCheckCode(String jsonstr) {
        JSONObject jsonobj = JSONObject.parseObject(jsonstr);
        //判断是否出验证码
        if (jsonobj.get("status") != null && jsonobj.get("status").toString().equals("checkcode")) {
            return true;
        }
        return false;
    }

    public static void main(String[] args) {
        CookieStore cookieStore = null;
        String s = CheckCodeSubmit.submit("http://regcheckcode.taobao.com/auction/checkcode?sessionID=839d1aad8777b94cc9e2ad6123e07215", "http://sec.taobao.com/query.htm?action=QueryAction&event_submit_do_query=ok&smApp=ratemanager&smPolicy=ratemanager-checkcode&smCharset=GBK&smTag=MTgzLjEyOS4xNTkuMTY2&smReturn=http%3A%2F%2Frate.taobao.com%2Fmember_rate.htm%3Fcontent%3D1%26identity%3D1%26result%3D%26page%3D2%26_ksTS%3D1396573487139_241%26direction%3D0%26callback%3Dshop_rate_list%26user_id%3DUvGgyvFvYvGQT%26rater%3D0%26from%3Drate&smSign=krCiwbh1QmH6oG5L0rGO%2FQ%3D%3D", "839d1aad8777b94cc9e2ad6123e07215",cookieStore);
    }
}
